﻿using log4net.Core;
using log4net.ElasticSearch.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

namespace log4net.ElasticSearch
{
    internal class LogManager
    {

        public static String ConvertToJson(LogModel logModel)
        {
            return new JavaScriptSerializer().Serialize(logModel);
        }
        public static String ConvertToJson(LogModel[] logModels)
        {
            return new JavaScriptSerializer().Serialize(logModels);
        }
        public static LogModel[] ConvertToModel(LoggingEvent[] events)
        {
            if (events == null) return null;
            return events.Select(x => ConvertToModel(x)).ToArray();
        }

        public static LogModel ConvertToModel(LoggingEvent loggingEvent)
        {
            var logModel = new LogModel
            {
                loggerName = loggingEvent.LoggerName,
                domain = loggingEvent.Domain,
                identity = loggingEvent.Identity,
                threadName = loggingEvent.ThreadName,
                userName = loggingEvent.UserName,
                timeStamp = loggingEvent.TimeStamp.ToUniversalTime().ToString("O"),
                exception = loggingEvent.ExceptionObject == null ? new object() : ExceptionModel.Create(loggingEvent.ExceptionObject),
                message = loggingEvent.RenderedMessage,
                fix = loggingEvent.Fix.ToString(),
                hostName = Environment.MachineName,
                level = loggingEvent.Level == null ? null : loggingEvent.Level.DisplayName
            };

            // Added special handling of the MessageObject since it may be an exception. 
            // Exception Types require specialized serialization to prevent serialization exceptions.
            if (loggingEvent.MessageObject != null && loggingEvent.MessageObject.GetType() != typeof(string))
            {
                if (loggingEvent.MessageObject is Exception)
                {
                    logModel.messageObject = ExceptionModel.Create((Exception)loggingEvent.MessageObject);
                }
                else
                {
                    logModel.messageObject = loggingEvent.MessageObject;
                }
            }
            else
            {
                logModel.messageObject = new object();
            }

            if (loggingEvent.LocationInformation != null)
            {
                logModel.className = loggingEvent.LocationInformation.ClassName;
                logModel.fileName = loggingEvent.LocationInformation.FileName;
                logModel.lineNumber = loggingEvent.LocationInformation.LineNumber;
                logModel.fullInfo = loggingEvent.LocationInformation.FullInfo;
                logModel.methodName = loggingEvent.LocationInformation.MethodName;
            }

            //AddProperties(loggingEvent, logEvent);

            return logModel;
        }
    }
}
